const express = require("express")
router = express.Router()
const config = require("../config/config")
const axios = require("axios")
const User = require("../mongodb/user")
const ZF = require("../mongodb/zf")
const mongoose = require("mongoose")
const CircularJSON = require('circular-json');
//设置一些状态
let result = { status: 200, data: null, state: "成功" }
router.post("/zf/list", async (req, res) => {

    try {
        let { openid } = req.body
        // 查用户信息
        let userInfo = await User.findOne({ openid })
        console.log(userInfo)
        let list = userInfo.zflistId
        let data = await ZF.find({ _id: { $in: list } })
        console.log(list)
        result.data = data
        result.state = "成功"
        res.send(result)

        // 循环查询
    } catch {
        console.log(err)
        result.status = 500
        result.state = "失败"
        res.status = 500
        res.state = "服务器错误"
        res.send(result)
    }
})

// 中风预测
router.post("/zf/predict", async (req, res) => {

    try {
        let { ever_married, gender, Residence_type, work_type, smoking_status, hypertension, bmi, heart_disease, avg_glucose_level, age, height, weight, openid } = req.body
        if (ever_married && gender && height && weight && Residence_type && work_type && smoking_status && hypertension && heart_disease && age && avg_glucose_level && bmi && openid) {
            result.error = "请上传所有的指标"
            result.state = "失败"
            res.json(result)
            return
        }
        console.log(req.body)
        // 生成结果
        let resultdata = CircularJSON.stringify(await axios.post(`${config.zfHost.host}:${config.zfHost.port}/predict`, { ever_married, gender, Residence_type, work_type, smoking_status, hypertension, bmi, heart_disease, avg_glucose_level, age }))
        result.result = JSON.parse(resultdata).data
        let resultdata2 = result.result.prediction
        // 返回建议
        let advice = getResult({ smoking_status, bmi, hypertension, heart_disease, avg_glucose_level, prediction: resultdata2 })
        result.advice = advice

        // 写入数据库
        newZF = new ZF({ ever_married, gender, Residence_type, work_type, smoking_status, hypertension, bmi, heart_disease, avg_glucose_level, age, height, weight, userId: openid, advice: advice.advice_str, result: resultdata2 })
        let newData = await newZF.save()
        result.data = newData
        let _id = newData._id
        // 在用户表中插入数据
        let userInfo = await User.updateOne(
            { openid: openid }, // 查询条件，根据您的需要进行更改
            { $push: { zflistId: _id } } // 使用 $push 操作符将新元素添加到数组末尾
        )
        console.log(userInfo)
        console.log(newData)
        res.send(result)



    } catch (err) {
        console.log(err)
        result.status = 500
        result.state = "失败"
        res.status = 500
        res.state = "服务器错误"
        res.send(result)
    }
})


//判断指标的逻辑算法
function getResult(data) {
    let { smoking_status, bmi, hypertension, heart_disease, avg_glucose_level, prediction } = data
    let advice = ["根据体检报告,"]
    if (bmi < 18.5) {
        advice.push("您体重过轻，应该建议逐渐增加饮食摄入量，以增加热量和营养素的摄入。可以增加含高蛋白质、高热量、易消化的食物，如肉类、鱼类、蛋类、豆类、坚果等，同时注意膳食均衡，摄入适量的脂肪、碳水化合物、膳食纤维、维生素和矿物质等。")
    }
    if (bmi >= 24 && bmi < 28) {
        advice.push("您体重超重,应该减少饮食中的高热量食物和含糖饮料，并增加蔬菜、水果和全谷类食物的摄入量。")
    }
    if (bmi >= 28) {
        advice.push("您体重严重超重,应该减少饮食中的高热量食物和含糖饮料，并增加蔬菜、水果和全谷类食物的摄入量。")
    }

    if (smoking_status == 0) {
        advice.push("您日常有吸烟习惯,应该减少吸烟量。如果患者暂时无法戒烟，建议尽量减少吸烟量。")
    }

    if (hypertension == 1) {
        advice.push("您患有高血压，应该加强体育锻炼，每周进行至少150分钟的中等强度有氧运动。")
    }
    if (heart_disease == 1) {
        advice.push("您患有心脏病,，应该选择低胆固醇、低饱和脂肪酸和低钠的饮食，减少红肉、加工食品和高糖食物的摄入。")
    }


    if (avg_glucose_level < 70) {
        advice.push("您血糖过高，应该限制食用高糖食物和高碳水化合物的食物，增加蔬菜、水果和全谷类食物的摄入。")
    }

    if (avg_glucose_level > 150) {
        advice.push("您血糖过低，应该分多次进食，避免长时间空腹，保持血糖稳定")
    }

    if (prediction) {
        advice.push("由模型计算得出，您患中风疾病可能性较大，需要进行进一步细致检查。")
    }
    if (!prediction) {
        advice.push("由预测模型得出，您患中风疾病可能性较小。")
    }
    let advice_str = ""

    for (const i of advice) {
        advice_str += i
    }
    return { advice_str }
}


module.exports = router